package com.jeff.android.lab.commonlib.router;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: duff
 * @date: 2019/3/14
 * @since: 1.0.0
 */
public class ThreadPoolFactory {

    static class DefaultThreadFactory implements ThreadFactory {
        private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);
        private final ThreadGroup mGroup;
        private final AtomicInteger mThreadNumber = new AtomicInteger(1);
        private final String mNamePrefix;

        DefaultThreadFactory() {
            SecurityManager securityManager = System.getSecurityManager();
            mGroup = (securityManager != null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup();
            mNamePrefix = "pool-" + POOL_NUMBER.getAndIncrement() + "-thread-";
        }

        public Thread newThread(Runnable runnable) {
            Thread thread = new Thread(mGroup, runnable, mNamePrefix + mThreadNumber.getAndIncrement(), 0);
            thread.setDaemon(true);
            thread.setPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
            return thread;
        }
    }

    private static final int DEF_CORE_POOL_SIZE = 8;
    private static final int DEF_MAX_POOL_SIZE = 128;
    private static final int KEEP_ALIVE_TIME = 1;

    public static ThreadPoolExecutor getExecutor(String name) {
        return getExecutor(name, DEF_CORE_POOL_SIZE, DEF_MAX_POOL_SIZE);
    }

    public static ThreadPoolExecutor getExecutor(String name, int corePoolSize, int maxPoolSize) {
        return new ThreadPoolExecutor(DEF_CORE_POOL_SIZE, DEF_MAX_POOL_SIZE,
                KEEP_ALIVE_TIME, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new DefaultThreadFactory());
    }

}
